<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="hAdd(1,0)">添加权限</el-button>
        </div>
        <!-- row-key="id"在表格中加入这个属性即可以完成树状结构 -->
        <el-table border :data="list" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button v-if="scope.row.type === 1" type="text" @click="hAdd(2,scope.row.id)">添加</el-button>
              <el-button type="text" @click="hEdit(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <el-dialog
      :visible.sync="showDialog"
      title="添加权限点"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="hClose"
    >
      <!-- 表单内容 -->
      <el-form ref="form" label-width="100px" :rules="rules" :model="formData">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model.trim="formData.name" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model.trim="formData.code" />
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input v-model.trim="formData.description" />
        </el-form-item>
        <el-form-item label="权限启用">
          <el-switch
            v-model="formData.enVisible"
            active-text="启用"
            active-value="1"
            inactive-text="不启用"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div style="text-align: right;">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="hSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { getPermissionList, addPermission, delPermission, getPermissionDetail, updatePermission } from '@/api/permission'
import { tree2 } from '@/utils/tree'
export default {
  name: 'Permissions',
  data() {
    const validCode = (rule, value, callback) => {
      // 添加时的校验：code不能重复
      let existCodeList = this.originList
      if (this.isEdit) {
        // 编辑时的校验: code能取自己
        existCodeList = this.originList.filter(item => item.id !== this.formData.id)
      }
      existCodeList.map(it => it.code).includes(value)
        ? callback(new Error(value + '已经占用'))
        : callback()
    }

    const validName = (rule, value, callback) => {
      // 添加时的校验： 名字不能取子元素的名字
      // 因为当前pid与FormData中的pid格式不同只能写两个等号
      // eslint-disable-next-line eqeqeq
      let existNameList = this.originList.filter(item => item.pid == this.formData.pid)
      if (this.isEdit) {
        // 编辑时的校验： 名字不能取兄弟（排除自己）的名字
        // 找兄弟，排除自己
        existNameList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      existNameList.map(it => it.name).includes(value)
        ? callback(new Error(value + '已经占用'))
        : callback()
    }
    return {
      list: [],
      showDialog: false,
      originList: [],
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      isEdit: false,
      rules: {
        name: [{ required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }],
        description: [{ required: true, message: '权限描述不能为空', trigger: 'blur' }],
        code: [{ required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }]
      }
    }
  },
  created() {
    // 获取权限列表数据
    this.loadPermissionList()
  },
  methods: {
    // 获取权限列表数据
    async loadPermissionList() {
      try {
        const { data } = await getPermissionList()
        this.originList = data.map(({ id, pid, name, code }) => ({ id, pid, name: name.trim(), code }))
        // 转为树状结构并赋值
        this.list = tree2(data)
      } catch (err) {
        console.log(err)
      }
    },
    // 添加权限
    hAdd(type, pid) {
      // enVisible	string
      // name	string
      // code	string
      // description	string
      // type	number 1:页面 2:按钮
      // pid	string
      this.showDialog = true
      this.formData.type = type
      this.formData.pid = pid
      this.isEdit = false
    },
    hSubmit() {
      // 兜底校验
      this.$refs.form.validate(valid => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    async doAdd() {
      try {
        // 发送请求
        await addPermission(this.formData)
        // 关闭弹层
        this.showDialog = false
        // 提示成功
        this.$message.success('添加权限成功')
        // 重新加载数据
        this.loadPermissionList()
        // 保存数据
      } catch (err) {
        console.log(err)
      }
    },
    // 关闭弹层时清空表单
    hClose() {
      this.formData = {}
      this.$refs.form.resetFields()
    },
    hDel(id) {
      this.$confirm('确定要删除吗').then(() => {
        this.doDel(id)
      }).catch(() => {})
    },
    // 删除
    async doDel(id) {
      try {
        await delPermission(id)
        this.$message.success('删除成功')
        this.loadPermissionList()
      } catch (err) {
        console.log(err)
      }
    },
    // 修改
    async hEdit(id) {
      // 获取详情数据
      try {
        const { data } = await getPermissionDetail(id)
        // console.log(res)
        this.formData = data
        this.showDialog = true
        this.isEdit = true
      } catch (err) {
        console.log(err)
      }
    },
    // 编辑
    async doEdit() {
      try {
        await updatePermission(this.formData)
        this.$message.success('修改成功')
        this.showDialog = false
        this.loadPermissionList()
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

